package com.haotian.User.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haotian.coder.constant.UserConstant;
import com.haotian.coder.exception.BusinessException;
import com.haotian.coder.exception.ErrorCode;
import com.haotian.coder.exception.ThrowUtils;
import com.haotian.coder.model.dto.user.UserQueryRequest;
import com.haotian.coder.model.vo.LoginUserVO;
import com.haotian.coder.model.vo.UserVO;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.haotian.coder.model.entity.User;
import com.haotian.User.mapper.UserMapper;
import com.haotian.User.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 服务层实现。
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 注销只要移除登陆态即可

        // 判断是否登陆
        Object user = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null){
            // 没有登陆报错
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登陆");
        }
        // 如果登陆了直接注销
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否登陆
        Object user = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登陆");
        }
        User currentUser = (User)user;
        // 从数据库中查询，保证查出来的用户都是最新的数据， 先从session中获取用户id，再利用id去查数据库中的用户
        Long userId = currentUser.getId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getId, userId);
        currentUser = this.mapper.selectOneByQuery(queryWrapper);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR,"用户不存在");
        return currentUser;
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StrUtil.hasBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"登陆参数为空!");
        }

        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号错误!");
        }

        if(userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码错误!");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getUserAccount, userAccount);
        queryWrapper.eq(User::getUserPassword, getEncryptPassword(userPassword));

        User user = this.mapper.selectOneByQuery(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在!");
        }

        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user);

        return getLoginUserVO(user);
    }

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1.校验参数,并检查参数的长度格式是否正确
        if(StrUtil.hasBlank(userAccount, userPassword, checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"登陆参数为空!");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短!");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短!");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入的密码不一致!");
        }


        // 2.查询数据库中是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getUserAccount, userAccount);
        long userCount = this.mapper.selectCountByQuery(queryWrapper);
        if (userCount > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户已存在!");
        }
        // 3.加密密码存入数据库中
        String  encryptPassword= getEncryptPassword(userPassword);
        // 4.插入数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserRole("user");
        user.setUserName("用户"+ RandomUtil.randomNumbers(4));
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR,"用户信息保存数据库失败！!");
        // 返回用户id
        return 0;
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        final String salt = "haotian";
        return DigestUtils.md5DigestAsHex((userPassword + salt).getBytes());
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq("id", id)
                .eq("userRole", userRole)
                .like("userAccount", userAccount)
                .like("userName", userName)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }



}
